package lupos;

import java.util.List;
import java.util.ArrayList;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/** 
 * The role of this file is to parse the 'annotationSet'
 * elements in FrameNet 1.3 annotation files. The format
 * of these elements is as follows:
 * 
 *   annotationSet @ID @status
 *     > layers
 *         > layer*
 *     > sentence @ID @aPos
 *         > text #PCDATA
 *         > parts-of-speech @type
 *             > pos*
 *             
 * There is a bug in the source files involving POS tags - 
 * see the code for details. 
 */

public class AnnotationSet {

	public String subCorpus; // comes from the parent element
	public String id;
	public String status;
	public List<Layer> layers = new ArrayList<Layer>();
	public String sentenceId;
	public String sentenceAPos;
	public String sentenceText;
	public String posType;
	public List<Pos> pos = new ArrayList<Pos>();
	
	public AnnotationSet(Element e, String sc) {
		subCorpus = sc;
		id = e.getAttribute("ID");
		status = e.getAttribute("status");
		NodeList ns = e.getChildNodes();
		for (int i=0;i<ns.getLength();i++) {
			Node n = ns.item(i);
			String s = n.getNodeName();
			if (s.equals("layers")) {
				NodeList ps = ((Element) n).getChildNodes();
				for (int j=0;j<ps.getLength();j++) {
					Node p = ps.item(j);
					if (p.getNodeName().equals("layer")) {
						layers.add(new Layer((Element) p));
					}
				}
			}
			else if (s.equals("sentence")) {
				Element f = (Element) n;
				sentenceId = f.getAttribute("ID");
				sentenceAPos = f.getAttribute("aPos");
				NodeList ps = f.getChildNodes();
				for (int j=0;j<ps.getLength();j++) {
					Node p = ps.item(j);
					if (p.getNodeName().equals("text")) {
						sentenceText = ((Element) p).getTextContent();
					}
					else if (p.getNodeName().equals("parts-of-speech")) {
						Element g = (Element) p;
						posType = g.getAttribute("type");
						NodeList qs = g.getChildNodes();
						for (int k=0;k<qs.getLength();k++) {
							Node q = qs.item(k);
							if (q.getNodeName().equals("pos")) {
								try {
									pos.add(new Pos((Element) q,sentenceText));
								}
								catch (StringIndexOutOfBoundsException x) {
									/* some POS tags at the end of an utterance are ill-formed,
									   ending before they start! e.g. lu9724, lu922, lu9087, lu9055, etc.
									   I just ignore them. */
								}
							}							
						}
					}
				}				
			}
		}		
	}
	
}
